// pages/profile/index.ts

Page({
  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: '',
    nickName: '',
  },
  onShow() {
    this.setData({
      avatarUrl: getApp().globalData.avatar,
      nickName: getApp().globalData.nickName,
    })
  },
  onChooseAvatar(e) {
    this.setData({
      avatarUrl: e.detail.avatarUrl,
    })
    getApp().globalData.avatar = e.detail.avatarUrl

    wx.getImageInfo({
      src: e.detail.avatarUrl,
      success: function (res) {
        // success
        const { path } = res
        wx.uploadFile({
          url: 'https://live-api.itheima.net/upload',
          filePath: path,
          name: 'file',
          header: {
            Authorization: 'Bearer ' + wx.getStorageSync('token'),
          },
          formData: {
            type: 'avatar',
          },
          success: function () {
            // success
            getApp().avatar = e.detail.avatarUrl
            wx.utils.toast('头像上传成功！')
          },
          fail: function () {
            // fail
            wx.utils.toast('上传失败！')
          },
        })
      },
    })
  },

  async getNickname(e) {
    const { data } = await wx.http.put('/userInfo', {
      nickName: e.detail.value,
    })
    if (data.code === 10000) {
      this.setData({
        nickName: e.detail.value,
      })
      getApp().globalData.nickname = e.detail.value
    } else {
      wx.utils.toast('修改昵称失败')
    }
  },
})
